# -*- coding: utf-8 -*-
import logging

from django.utils.html import strip_tags
from django.core.management.base import BaseCommand, CommandError
from django.contrib.postgres.search import SearchVector
from django.contrib.postgres.aggregates import StringAgg
from book.models import BookIndex, Book, BookAuthor


logger = logging.getLogger('book.index')


class Command(BaseCommand):
    help = 'fetch the specified book from allitebook.com'
    s = None

    def add_arguments(self, parser):
        parser.add_argument('--size', type=int, default=10,
                            help='batch size')
        parser.add_argument('--end', type=int, default=3, help='end page num')
        parser.add_argument('--c', type=int, default=4,
                            help='concurrent workers count')
        parser.add_argument('--m', type=str, default='thread',
                            help='thread or process')
        #parser.add_argument('--book_id', nargs='+', type=int)

    def handle(self, *args, **options):
        index = BookIndex.objects.values_list('index_at', flat=True).order_by(
            '-index_at').first() or '1970-01-01'
        vector = SearchVector('title', 'sub_title') + \
            SearchVector(StringAgg('tags__name', delimiter=' ')) + \
            SearchVector(StringAgg('authors__name', delimiter=' '))
        for book in Book.objects.annotate(document=vector).filter(updated_at__gte=index).prefetch_related('tags').prefetch_related('authors').order_by('updated_at')[0:options['size']]:
            try:
                book_index = BookIndex.objects.get(book=book)
            except BookIndex.DoesNotExist:
                book_index = BookIndex(book=book)

            book_index.tsv = book.document
            #book_index.index_at = datetime.datetime.now
            book_index.save()
